package cn.edu.qzuie.artist.module.td.service.work;

import cn.edu.qzuie.artist.framework.security.core.util.SecurityFrameworkUtils;
import cn.edu.qzuie.artist.module.td.controller.admin.worksimage.vo.WorksImageRespVO;
import cn.edu.qzuie.artist.module.td.controller.admin.worksimage.vo.WorksImageSaveReqVO;
import cn.edu.qzuie.artist.module.td.dal.dataobject.workscatagory.WorksCatagoryDO;
import cn.edu.qzuie.artist.module.td.dal.dataobject.worksimage.WorksImageDO;
import cn.edu.qzuie.artist.module.td.dal.mysql.worksimage.WorksImageMapper;
import cn.edu.qzuie.artist.module.td.service.workscatagory.WorksCatagoryService;
import cn.edu.qzuie.artist.module.td.service.worksimage.WorksImageService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.edu.qzuie.artist.module.td.controller.admin.work.vo.*;
import cn.edu.qzuie.artist.module.td.dal.dataobject.work.WorkDO;
import cn.edu.qzuie.artist.framework.common.pojo.PageResult;
import cn.edu.qzuie.artist.framework.common.pojo.PageParam;
import cn.edu.qzuie.artist.framework.common.util.object.BeanUtils;

import cn.edu.qzuie.artist.module.td.dal.mysql.work.WorkMapper;

import static cn.edu.qzuie.artist.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.edu.qzuie.artist.module.td.enums.ErrorCodeConstants.*;

/**
 * 作品 Service 实现类
 *
 * @author 泉信管理员
 */
@Service
@Validated
public class WorkServiceImpl extends ServiceImpl<WorkMapper,WorkDO> implements WorkService {

    @Resource
    private WorkMapper workMapper;

    @Resource
    private WorksCatagoryService worksCatagoryService;

    @Resource
    private WorksImageMapper worksImageMapper;

    @Override
    @Transactional // 事务管理
    public Long createWork(WorkSaveReqVO createReqVO) {
        //获取用户id
        Long userId= SecurityFrameworkUtils.getLoginUserId();
        //获取用户昵称
        String nickName = SecurityFrameworkUtils.getLoginUserNickname();

        createReqVO.setUserId(userId); // 插入用户id
        createReqVO.setNickName(nickName); // 插入用户昵称

        // 插入
        WorkDO work = BeanUtils.toBean(createReqVO, WorkDO.class);
        workMapper.insert(work);
        //插入图片
        WorksImageDO worksImage = new WorksImageDO();
        worksImage.setWorkId(work.getId()); // 插入id
        worksImage.setWorkName(work.getWorkName()); // 插入作品名称
        worksImage.setImgSrc(createReqVO.getImgSrc()); //插入封面
        worksImageMapper.insert(worksImage);

        // 返回
        return work.getId();

        // 批量插入图片
//        for (String imgSrc : createReqVO.getImgSrcs()) {
//            WorksImageDO worksImage = new WorksImageDO();
//            worksImage.setWorkId(work.getId()); // 插入id
//            worksImage.setImgSrc(imgSrc); //插入图片
//            worksImageMapper.insert(worksImage);
//        }


    }

    @Override
    @Transactional
    public void updateWork(WorkSaveReqVO updateReqVO) {
        // 校验存在
        validateWorkExists(updateReqVO.getId());
        // 更新
        WorkDO updateObj = BeanUtils.toBean(updateReqVO, WorkDO.class);
        workMapper.updateById(updateObj);

        // 更新封面
        WorksImageDO worksImage = worksImageMapper.selectByWorkIdAndSort(updateReqVO.getId());
        worksImage.setImgSrc(updateReqVO.getImgSrc());
        worksImage.setWorkName(updateReqVO.getWorkName()); //更新作品名
        worksImageMapper.updateById(worksImage);
        worksImageMapper.updateWorkName(worksImage);

    }

    @Override
    public void deleteWork(Long id) {
        // 校验存在
        validateWorkExists(id);

        // 删除
        workMapper.deleteById(id);

        // 删除子作品的封面
        worksImageMapper.updateByWorkId(id);
    }

    private void validateWorkExists(Long id) {
        if (workMapper.selectById(id) == null) {
            throw exception(WORK_NOT_EXISTS);
        }
    }

//    @Override
//    public WorkDO getWork(Long id) {
//        return workMapper.selectById(id);
//    }
    //
    @Override
    @Transactional
    public WorkRespVO getWorks(Long id) {
        // 先查询td_work表中的数据
        WorkDO workDO =  workMapper.selectById(id);
        // 判断是否为空
        if (workDO == null){
            throw new RuntimeException("作品不存在");
        }
        // 获取到分类编号，通过分类编号去查询td_work_category表中的parent_id
        Long catagoryId = workDO.getCatagoryId();
        // 查询td_work_category表中的数据
        WorksCatagoryDO worksCatagoryDO = worksCatagoryService.getById(catagoryId);
        // 判断是否为空
        if (worksCatagoryDO == null){
            throw new RuntimeException("作品分类不存在");
        }
        // 查询 td_work_image 表中的所有相关图片数据
//        List<WorksImageDO> worksImageList = worksImageService.getByWorkId(id);
        WorksImageDO worksImage = worksImageMapper.selectByWorkIdAndSort(id);
        // 将DO转换为VO
        return convertToVO(workDO,worksCatagoryDO,worksImage);
    }
    /**
     * 将 DO 转换为 VO
     */
    private WorkRespVO convertToVO(WorkDO work, WorksCatagoryDO worksCatagoryDO,WorksImageDO worksImage) {
        WorkRespVO workRespVO = new WorkRespVO();
        BeanUtils.copyProperties(work, workRespVO); // 对象属性拷贝
        workRespVO.setParentId(worksCatagoryDO.getParentId()); // 设置额外字段
        // 提取所有图片路径
//        List<String> imageUrls = worksImageList.stream()
//                .map(WorksImageDO::getImgSrc)
//                .toList();
        workRespVO.setImgSrc(worksImage.getImgSrc()); // 设置图片列表
        //workRespVO.setDescribes(worksImageList.get(0).getDescribes());
        return workRespVO;
    }


    @Override
    public WorkRespVO getWork(Long id) {
        return workMapper.selectByIdWithParentId(id);
    }

    @Override
    public PageResult<WorkDO> getWorkPage(WorkPageReqVO pageReqVO) {
        return workMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<WorkMultiplePagesVO> getWorkWithcategoryName(WorkPageReqVO pageReqVO) {
        WorkPageReqVO reqVO = new WorkPageReqVO();
        BeanUtils.copyProperties(pageReqVO,reqVO);
        return workMapper.selectWorkWithCategoryName(pageReqVO,reqVO);
    }
    // 修改作品是否发布状态
    @Override
    public void updateWorkPublished(Boolean published, Long id) {
        workMapper.update(null,
                new UpdateWrapper<WorkDO>()
                        .set("published",published)
                        .eq("id",id)
        );
    }

    /**
     * 获取作品集与说明
     * @param id
     * @return
     */
    @Override
    public List<WorGetImageRespVO> getImagesWithDescribes(Long id) {

        return worksImageMapper.selectByImageWithDescribes(id);
    }


}